<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="1024" @ok="handleSubmit">
    <BasicForm @register="registerForm" ref="formRef" />

    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
      <a-tab-pane tab="工作日规则" key="psWorkingCalendarRule" :forceRender="true">
        <JVxeTable
          keep-source
          resizable
          ref="psWorkingCalendarRule"
          :loading="psWorkingCalendarRuleTable.loading"
          :columns="psWorkingCalendarRuleTable.columns"
          :dataSource="psWorkingCalendarRuleTable.dataSource"
          :height="340"
          :rowNumber="true"
          :rowSelection="true"
          :disabled="formDisabled"
          :toolbar="true"
        />
      </a-tab-pane>
      <a-tab-pane tab="班次规则" key="psWorkingCalendarClassesRule" :forceRender="true">
        <JVxeTable
          keep-source
          resizable
          ref="psWorkingCalendarClassesRule"
          :loading="psWorkingCalendarClassesRuleTable.loading"
          :columns="psWorkingCalendarClassesRuleTable.columns"
          :dataSource="psWorkingCalendarClassesRuleTable.dataSource"
          :height="340"
          :rowNumber="true"
          :rowSelection="true"
          :disabled="formDisabled"
          :toolbar="true"
        >
          <template #workCalendarSlot="props">
            <a-input-search @search="handleView(props)" placeholder="请选择班次" v-model:value="props.row.workCalendarName"></a-input-search>
          </template>
        </JVxeTable>
      </a-tab-pane>
      <a-tab-pane tab="工作日历详情信息" key="psWorkingCalendarParticulars" :forceRender="true">
        <JVxeTable
          keep-source
          resizable
          ref="psWorkingCalendarParticulars"
          :loading="psWorkingCalendarParticularsTable.loading"
          :columns="psWorkingCalendarParticularsTable.columns"
          :dataSource="psWorkingCalendarParticularsTable.dataSource"
          :height="340"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="false"
        />
      </a-tab-pane>
    </a-tabs>
  </BasicModal>
  <!-- 班次 -->
  <shiftManagementSelectModel
    @register="shiftManagementRegModal"
    @getSelectResult="shiftManagementhandleSuccess"
    v-bind="getBindValue"
  ></shiftManagementSelectModel>
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive } from 'vue';
import { useMessage } from '/src/hooks/web/useMessage';
import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { JVxeTable } from '/@/components/jeecg/JVxeTable';
import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods';
import { dateUtil } from '/@/utils/dateUtil';
import {
  formSchema,
  psWorkingCalendarRuleColumns,
  psWorkingCalendarClassesRuleColumns,
  psWorkingCalendarParticularsColumns,
} from '../PsWorkingCalendar.data';
import {
  saveOrUpdate,
  psWorkingCalendarRuleList,
  psWorkingCalendarClassesRuleList,
  psWorkingCalendarParticularsList,
} from '../PsWorkingCalendar.api';
import shiftManagementSelectModel from '/@/views/components/shiftManagementSelectModel.vue';

const { createMessage } = useMessage();
// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const title = ref('新增');
const formDisabled = ref(false);
const refKeys = ref(['psWorkingCalendarRule', 'psWorkingCalendarClassesRule', 'psWorkingCalendarParticulars']);
const activeKey = ref('psWorkingCalendarRule');
const psWorkingCalendarRule = ref();
const psWorkingCalendarClassesRule = ref();
const psWorkingCalendarParticulars = ref();
const tableRefs = { psWorkingCalendarRule, psWorkingCalendarClassesRule, psWorkingCalendarParticulars };
const psWorkingCalendarRuleTable = reactive({
  loading: false,
  dataSource: [

  ],
  columns: psWorkingCalendarRuleColumns,
});
const psWorkingCalendarClassesRuleTable = reactive({
  loading: false,
  dataSource: [],
  columns: psWorkingCalendarClassesRuleColumns,
});
const psWorkingCalendarParticularsTable = reactive({
  loading: false,
  dataSource: [],
  columns: psWorkingCalendarParticularsColumns,
});

//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 80,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 8 },
});
//方法配置
const [handleChangeTabs, handleSubmit, requestSubTableData, formRef] = useJvxeMethod(
  requestAddOrEdit,
  classifyIntoFormData,
  tableRefs,
  activeKey,
  refKeys
);

//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //重置表单
  await reset();
  setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
  isUpdate.value = !!data?.isUpdate;
  formDisabled.value = data.title == '详情' ? true : false;
  title.value = data.title;
  if (unref(isUpdate)) {
    //表单赋值
    await setFieldsValue({
      ...data.record,
    });
    requestSubTableData(psWorkingCalendarRuleList, { id: data?.record?.id }, psWorkingCalendarRuleTable);
    requestSubTableData(psWorkingCalendarClassesRuleList, { id: data?.record?.id }, psWorkingCalendarClassesRuleTable);
    requestSubTableData(psWorkingCalendarParticularsList, { id: data?.record?.id }, psWorkingCalendarParticularsTable);
  }
  // 隐藏底部时禁用整个表单  改为 title为详情时  禁用表单
  setProps({ disabled: data.title == '详情' ? true : false });
});

async function reset() {
  await resetFields();
  activeKey.value = 'psWorkingCalendarRule';
  psWorkingCalendarRuleTable.dataSource = [];
  psWorkingCalendarClassesRuleTable.dataSource = [];
}
function classifyIntoFormData(allValues) {
  let main = Object.assign({}, allValues.formValue);
  console.log(allValues);

  return {
    ...main, // 展开
    psWorkingCalendarRuleList: allValues.tablesValue[0].tableData,
    psWorkingCalendarClassesRuleList: allValues.tablesValue[1].tableData,
    psWorkingCalendarParticularsList: allValues.tablesValue[2].tableData,
  };
}
//表单提交事件
async function requestAddOrEdit(values) {
  try {
    setModalProps({ confirmLoading: true });

    const startTime = dateUtil(values.startTime);
    const endTime = dateUtil(values.endTime);
    if (startTime.toDate().getTime() >= endTime.toDate().getTime()) {
      throw new Error('开始日期必须小于结束日期');
    }

    //提交表单
    await saveOrUpdate(values, isUpdate.value);
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
  } catch (err: any) {
    createMessage.error(err.message);
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
const [shiftManagementRegModal, { openModal: openShiftManagementModal }] = useModal();
const getBindValue = Object.assign({}, '');
var index: number | null = null;

//打开选择班次
function handleView(props) {
  index = props.params.$rowIndex;
  openShiftManagementModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//班次回写
function shiftManagementhandleSuccess(val, _values) {
  if (index != null) {
    psWorkingCalendarClassesRuleTable.dataSource = psWorkingCalendarClassesRule.value!.getTableData();
    psWorkingCalendarClassesRuleTable.dataSource[index].workCalendarName = val[0].label;
    psWorkingCalendarClassesRuleTable.dataSource[index].workCalendarId = val[0].value;
  }
}
</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-calendar-picker) {
  width: 100%;
}
</style>
